<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta name="theme-color" content="#222"><script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script><link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet"><style>.pace .pace-progress{background:#1e92fb;height:3px}.pace .pace-progress-inner{box-shadow:0 0 10px #1e92fb,0 0 5px #1e92fb}.pace .pace-activity{border-top-color:#1e92fb;border-left-color:#1e92fb}</style><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4"><link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4"><link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4"><link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222"><meta name="keywords" content="Vue,"><link rel="alternate" href="/atom.xml" title="It is written" type="application/atom+xml"><meta name="description" content="官方文档：https:&#x2F;&#x2F;vuex.vuejs.org&#x2F;zh&#x2F;"><meta property="og:type" content="article"><meta property="og:title" content="你必须知道的Vue之Vuex"><meta property="og:url" content="http://king-xiyu.gitee.io/article/9f02acae.html"><meta property="og:site_name" content="It is written"><meta property="og:description" content="官方文档：https:&#x2F;&#x2F;vuex.vuejs.org&#x2F;zh&#x2F;"><meta property="article:published_time" content="2020-07-13T13:09:42.000Z"><meta property="article:modified_time" content="2020-09-01T00:45:13.888Z"><meta property="article:author" content="King-XiYu"><meta property="article:tag" content="Vue"><meta name="twitter:card" content="summary"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Gemini",version:"5.1.4",sidebar:{position:"left",display:"post",offset:12,b2t:!0,scrollpercent:!0,onmobile:!1},fancybox:!0,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},duoshuo:{userId:"0",author:"博主"},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><link rel="canonical" href="http://king-xiyu.gitee.io/article/9f02acae.html"><title>你必须知道的Vue之Vuex | It is written</title><meta name="generator" content="Hexo 4.2.0"></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">It is written</span><span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"> <button><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br> 首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br> 标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br> 分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br> 归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br> 关于</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br> 搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i></span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"> <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="http://king-xiyu.gitee.io/article/9f02acae.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="King-XiYu"><meta itemprop="description" content=""><meta itemprop="image" content="http://ww1.sinaimg.cn/large/007WurYGgy1ge8nxttd9nj302s02s0si.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="It is written"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">你必须知道的Vue之Vuex</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-13T21:09:42+08:00">2020-07-13</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于&#58;</span> <time title="更新于" itemprop="dateModified" datetime="2020-09-01T08:45:13+08:00">2020-09-01</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/" itemprop="url" rel="index"><span itemprop="name">技术栈</span></a></span> ， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span><a href="/article/9f02acae.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/article/9f02acae.html" itemprop="commentCount"></span></a></span> <span id="/article/9f02acae.html" class="leancloud_visitors" data-flag-title="你必须知道的Vue之Vuex"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数&#58;</span><span class="leancloud-visitors-count"></span></span><div class="post-wordcount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i></span> <span class="post-meta-item-text">字数统计&#58;</span> <span title="字数统计">2.9k 字</span> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-clock-o"></i></span> <span class="post-meta-item-text">阅读时长 &asymp;</span> <span title="阅读时长">12 分钟</span></div></div></header><div class="post-body" itemprop="articleBody"><p>官方文档：<a href="https://vuex.vuejs.org/zh/" target="_blank" rel="noopener">https://vuex.vuejs.org/zh/</a></p><a id="more"></a><h1 id="什么是-Vuex-？"><a href="#什么是-Vuex-？" class="headerlink" title="什么是 Vuex ？"></a>什么是 Vuex ？</h1><p>Vuex 是一个专为 Vue.js 应用程序开发的状态管理插件。它采用集中式存储管理应用的所有组件的状态，而更改状态的唯一方法是提交 mutation，例 <code>this.$store.commit(&#39;SET_VIDEO_PAUSE&#39;, video_pause)</code>，<code>SET_VIDEO_PAUSE</code> 为 mutations 属性中定义的方法。</p><h1 id="Vuex-解决了什么问题？"><a href="#Vuex-解决了什么问题？" class="headerlink" title="Vuex 解决了什么问题？"></a>Vuex 解决了什么问题？</h1><p>解决了两个问题</p><ul><li>多个组件依赖于同一状态时，对于多层嵌套的组件的传参将会非常繁琐，并且对于兄弟组件间的状态传递无能为力。</li><li>来自不同组件的行为需要变更同一状态。以往采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱，通常会导致无法维护的代码</li></ul><h1 id="什么时候用-Vuex-？"><a href="#什么时候用-Vuex-？" class="headerlink" title="什么时候用 Vuex ？"></a>什么时候用 Vuex ？</h1><p>当项目遇到以下两种场景时</p><ul><li>多个组件依赖于同一状态时。</li><li>来自不同组件的行为需要变更同一状态。</li></ul><h1 id="怎么引用-Vuex-？"><a href="#怎么引用-Vuex-？" class="headerlink" title="怎么引用 Vuex ？"></a>怎么引用 Vuex ？</h1><ul><li><p>先安装依赖 <code>npm install vuex --save</code></p></li><li><p>在项目目录src中建立store文件夹</p></li><li><p>在store文件夹下新建index.js文件，写入</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span>;</span><br><span class="line"><span class="keyword">import</span> Vuex <span class="keyword">from</span> <span class="string">'vuex'</span>;</span><br><span class="line">Vue.use(Vuex);</span><br><span class="line"><span class="comment">//不是在生产环境debug为true</span></span><br><span class="line"><span class="keyword">const</span> debug = process.env.NODE_ENV !== <span class="string">'production'</span>;</span><br><span class="line"><span class="comment">//创建Vuex实例对象</span></span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    strict:debug,<span class="comment">//在不是生产环境下都开启严格模式</span></span><br><span class="line">    state:&#123;</span><br><span class="line">    &#125;,</span><br><span class="line">    getters:&#123;</span><br><span class="line">    &#125;,</span><br><span class="line">    mutations:&#123;</span><br><span class="line">    &#125;,</span><br><span class="line">    actions:&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> store;</span><br></pre></td></tr></table></figure></li><li><p>然后再main.js文件中引入Vuex，这么写</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span>;</span><br><span class="line"><span class="keyword">import</span> App <span class="keyword">from</span> <span class="string">'./App.vue'</span>;</span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'./store'</span>;</span><br><span class="line"><span class="keyword">const</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    store:store,</span><br><span class="line">    render: <span class="function"><span class="params">h</span> =&gt;</span> h(App)</span><br><span class="line">&#125;).$mount(<span class="string">'#app'</span>)</span><br></pre></td></tr></table></figure></li></ul><h1 id="Vuex-的5个核心属性是什么？"><a href="#Vuex-的5个核心属性是什么？" class="headerlink" title="Vuex 的5个核心属性是什么？"></a>Vuex 的5个核心属性是什么？</h1><p>分别是 state、getters、mutations、actions、modules。</p><h1 id="Vuex-中状态存储在哪里，怎么改变它？"><a href="#Vuex-中状态存储在哪里，怎么改变它？" class="headerlink" title="Vuex 中状态存储在哪里，怎么改变它？"></a>Vuex 中状态存储在哪里，怎么改变它？</h1><p>存储再state中，改变Vuex中的状态的唯一途径就是显式地提交（commit）mutation。</p><h1 id="Vuex中状态是对象时，使用时要注意什么？"><a href="#Vuex中状态是对象时，使用时要注意什么？" class="headerlink" title="Vuex中状态是对象时，使用时要注意什么？"></a>Vuex中状态是对象时，使用时要注意什么？</h1><p>因为对象是引用类型，复制后改变属性还是会影响原始数据，这样会改变state里面的状态，是不允许的，所以先用深度克隆赋值对象，再修改。</p><h1 id="怎么在组件中批量使用-Vuex-的-state-状态？"><a href="#怎么在组件中批量使用-Vuex-的-state-状态？" class="headerlink" title="怎么在组件中批量使用 Vuex 的 state 状态？"></a>怎么在组件中批量使用 Vuex 的 state 状态？</h1><p>使用 mapState 辅助函数，利用对象展开运算符将 state 混入 computed 对象中</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;mapState&#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    computed:&#123;</span><br><span class="line">        ...mapState([<span class="string">'name'</span>,<span class="string">'age'</span>])</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="Vuex-中要从-state-派生一些状态出来，且多个组件使用它，该怎么做？"><a href="#Vuex-中要从-state-派生一些状态出来，且多个组件使用它，该怎么做？" class="headerlink" title="Vuex 中要从 state 派生一些状态出来，且多个组件使用它，该怎么做？"></a>Vuex 中要从 state 派生一些状态出来，且多个组件使用它，该怎么做？</h1><p>使用 getter 属性，相当于 Vue 中的计算属性 computed ，只有原状态改变派生状态才会改变。</p><p>getter 接收两个参数，第一个是 state ，第二个是 getters （可以用来访问其他 getter）。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    state: &#123;</span><br><span class="line">        price: <span class="number">10</span>,</span><br><span class="line">        number: <span class="number">10</span>,</span><br><span class="line">        discount: <span class="number">0.7</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    getters: &#123;</span><br><span class="line">        total: <span class="function"><span class="params">state</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> state.price * state.number</span><br><span class="line">        &#125;,</span><br><span class="line">        discountTotal: <span class="function">(<span class="params">state, getters</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> state.discount * getters.total</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><p>然后在组件中可以用计算属性 cpmputed 通过 <code>this.$store.getters.total</code> 这样来访问这些派生状态。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">    total() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.$store.getters.total</span><br><span class="line">    &#125;,</span><br><span class="line">    discountTotal() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.$store.getters.discountTotal</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="怎么通过-getter-来实现在组件内可以通过特定条件来获取-state-的状态？"><a href="#怎么通过-getter-来实现在组件内可以通过特定条件来获取-state-的状态？" class="headerlink" title="怎么通过 getter 来实现在组件内可以通过特定条件来获取 state 的状态？"></a>怎么通过 getter 来实现在组件内可以通过特定条件来获取 state 的状态？</h1><p>通过让 getter 返回一个函数，来实现给 getter 传参。然后通过参数来进行判断从而获取 state 中满足要求的状态。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    state: &#123;</span><br><span class="line">        todos: [</span><br><span class="line">            &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">text</span>: <span class="string">'...'</span>, <span class="attr">done</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">            &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">text</span>: <span class="string">'...'</span>, <span class="attr">done</span>: <span class="literal">false</span> &#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">    getters: &#123;</span><br><span class="line">        getTodoById: <span class="function">(<span class="params">state</span>) =&gt;</span> <span class="function">(<span class="params">id</span>) =&gt;</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> state.todos.find(<span class="function"><span class="params">todo</span> =&gt;</span> todo.id === id)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><p>然后再组件中可以用计算属性 computed 通过 <code>this.$store.getters.getTodoById(2)</code> 这样来访问这些派生状态。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">computed: &#123;</span><br><span class="line">    getTodoById() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.$store.getters.getTodoById</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br><span class="line">mounted()&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.getTodoById(<span class="number">2</span>).done) <span class="comment">// false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="怎么在组件中批量使用-Vuex-的-getter-属性"><a href="#怎么在组件中批量使用-Vuex-的-getter-属性" class="headerlink" title="怎么在组件中批量使用 Vuex 的 getter 属性"></a>怎么在组件中批量使用 Vuex 的 getter 属性</h1><p>使用 mapGetters 辅助函数，利用对象展开运算符将 getter 混入 computed 对象中</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;mapGetters&#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    computed:&#123;</span><br><span class="line">        ...mapGetters([<span class="string">'total'</span>,<span class="string">'discountTotal'</span>])</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="怎么再组件中批量给-Vuex-的-getter-属性取别名并使用"><a href="#怎么再组件中批量给-Vuex-的-getter-属性取别名并使用" class="headerlink" title="怎么再组件中批量给 Vuex 的 getter 属性取别名并使用"></a>怎么再组件中批量给 Vuex 的 getter 属性取别名并使用</h1><p>使用 mapGetters 辅助函数，利用对象展开运算符将 getter 混入 computed 对象中</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;mapGetters&#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    computed:&#123;</span><br><span class="line">        ...mapGetters(&#123;</span><br><span class="line">            myTotal:<span class="string">'total'</span>,</span><br><span class="line">            myDiscountTotal:<span class="string">'discountTotal'</span>,</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="在-Vuex-的-state-中有个状态-number-表示货物数量，在组件怎么改变它。"><a href="#在-Vuex-的-state-中有个状态-number-表示货物数量，在组件怎么改变它。" class="headerlink" title="在 Vuex 的 state 中有个状态 number 表示货物数量，在组件怎么改变它。"></a>在 Vuex 的 state 中有个状态 number 表示货物数量，在组件怎么改变它。</h1><p>首先要在 mutations 中注册一个 mutation</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    state: &#123;</span><br><span class="line">        number: <span class="number">10</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    mutations: &#123;</span><br><span class="line">        SET_NUMBER(state,data)&#123;</span><br><span class="line">            state.number=data;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><p>在组件中使用 <code>this.$store.commit</code> 提交 mutation，改变 number</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.$store.commit(<span class="string">'SET_NUMBER'</span>, <span class="number">10</span>)</span><br></pre></td></tr></table></figure><h1 id="在-Vuex-中使用-mutation-要注意什么。"><a href="#在-Vuex-中使用-mutation-要注意什么。" class="headerlink" title="在 Vuex 中使用 mutation 要注意什么。"></a>在 Vuex 中使用 mutation 要注意什么。</h1><p>mutation 必须是同步函数</p><h1 id="在组件中多次提交同一个-mutation，怎么写使用更方便。"><a href="#在组件中多次提交同一个-mutation，怎么写使用更方便。" class="headerlink" title="在组件中多次提交同一个 mutation，怎么写使用更方便。"></a>在组件中多次提交同一个 mutation，怎么写使用更方便。</h1><p>使用 mapMutations 辅助函数，在组件中这么使用</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; mapMutations &#125; <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line">methods:&#123;</span><br><span class="line">    ...mapMutations(&#123;</span><br><span class="line">        setNumber:<span class="string">'SET_NUMBER'</span>,</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>然后调用 <code>this.setNumber(10)</code> 相当调用 <code>this.$store.commit(&#39;SET_NUMBER&#39;,10)</code></p><h1 id="Vuex-中-action-和-mutation-有什么区别？"><a href="#Vuex-中-action-和-mutation-有什么区别？" class="headerlink" title="Vuex 中 action 和 mutation 有什么区别？"></a>Vuex 中 action 和 mutation 有什么区别？</h1><ul><li><p>action 提交的是 mutation ，而不是直接变更状态。mutation 可以直接变更状态。</p></li><li><p>action 可以包含任意异步操作。mutation 只能是同步操作。</p></li><li><p>提交方式不同，action 是用 <code>this.$store.dispatch(&#39;ACTION_NAME&#39;, data)</code> 来提交。mutation 是用 <code>this.$store.commit(&#39;SET_NUMBER&#39;,10)</code> 来提交。</p></li><li><p>接收参数不同，mutation 第一个参数是 state，而 action 第一个参数是 context ，其包含了</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    state,      <span class="comment">// 等同于 `store.state`，若在模块中则为局部状态</span></span><br><span class="line">    rootState,  <span class="comment">// 等同于 `store.state`，只存在于模块中</span></span><br><span class="line">    commit,     <span class="comment">// 等同于 `store.commit`</span></span><br><span class="line">    dispatch,   <span class="comment">// 等同于 `store.dispatch`</span></span><br><span class="line">    getters,    <span class="comment">// 等同于 `store.getters`</span></span><br><span class="line">    rootGetters <span class="comment">// 等同于 `store.getters`，只存在于模块中</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li></ul><h1 id="Vuex-中-action-和-mutation-有什么相同点？"><a href="#Vuex-中-action-和-mutation-有什么相同点？" class="headerlink" title="Vuex 中 action 和 mutation 有什么相同点？"></a>Vuex 中 action 和 mutation 有什么相同点？</h1><p>第二参数都可以接收外部提交时传来的参数。<code>this.$store.dispatch(&#39;ACTION_NAME&#39;,data)</code> 和 <code>this.$store.commit(&#39;SET_NUMBER&#39;,10)</code></p><h1 id="在组件中多次提交同一个-action-，怎么写使用更方便。"><a href="#在组件中多次提交同一个-action-，怎么写使用更方便。" class="headerlink" title="在组件中多次提交同一个 action ，怎么写使用更方便。"></a>在组件中多次提交同一个 action ，怎么写使用更方便。</h1><p>使用 mapActions 辅助函数，在组件中这么使用</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">methods:&#123;</span><br><span class="line">    ...mapActions(&#123;</span><br><span class="line">        setNumber:<span class="string">'SET_NUMBER'</span>,</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>然后调用 <code>this.setNumber(10)</code> 相当调用 <code>this.$store.dispatch(&#39;SET_NUMBER&#39;,10)</code></p><h1 id="Vuex-中-action-通常是异步的，那么如何知道-action-什么时候结束呢？"><a href="#Vuex-中-action-通常是异步的，那么如何知道-action-什么时候结束呢？" class="headerlink" title="Vuex 中 action 通常是异步的，那么如何知道 action 什么时候结束呢？"></a>Vuex 中 action 通常是异步的，那么如何知道 action 什么时候结束呢？</h1><p>在 action 函数中返回 Promise ，然后在提交时候用 then 处理</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">actions:&#123;</span><br><span class="line">    SET_NUMBER_A(&#123;commit&#125;,data)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span>&#123;</span><br><span class="line">            setTimeout(<span class="function"><span class="params">()</span> =&gt;</span>&#123;</span><br><span class="line">                commit(<span class="string">'SET_NUMBER'</span>,<span class="number">10</span>);</span><br><span class="line">                resolve();</span><br><span class="line">            &#125;,<span class="number">2000</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">this</span>.$store.dispatch(<span class="string">'SET_NUMBER_A'</span>).then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><h1 id="Vuex-中有两个-action，分别是-actionA-和-actionB，其内都是异步操作，在-actionB-要提交-actionA，需在-actionA-处理结束在处理其他操作，怎么实现"><a href="#Vuex-中有两个-action，分别是-actionA-和-actionB，其内都是异步操作，在-actionB-要提交-actionA，需在-actionA-处理结束在处理其他操作，怎么实现" class="headerlink" title="Vuex 中有两个 action，分别是 actionA 和 actionB，其内都是异步操作，在 actionB 要提交 actionA，需在 actionA 处理结束在处理其他操作，怎么实现?"></a>Vuex 中有两个 action，分别是 actionA 和 actionB，其内都是异步操作，在 actionB 要提交 actionA，需在 actionA 处理结束在处理其他操作，怎么实现?</h1><p>利用 ES6 的 <code>async</code> 和 <code>await</code> 来实现。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">actions:&#123;</span><br><span class="line">    <span class="keyword">async</span> actionA(&#123;commit&#125;)&#123;</span><br><span class="line">        <span class="comment">//...</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">async</span> actionB(&#123;dispatch&#125;)&#123;</span><br><span class="line">        <span class="keyword">await</span> dispatch (<span class="string">'actionA'</span>)<span class="comment">//等待actionA完成</span></span><br><span class="line">        <span class="comment">// ... </span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="有用过-Vuex-模板吗，为什么要使用，怎么使用。"><a href="#有用过-Vuex-模板吗，为什么要使用，怎么使用。" class="headerlink" title="有用过 Vuex 模板吗，为什么要使用，怎么使用。"></a>有用过 Vuex 模板吗，为什么要使用，怎么使用。</h1><p>有，就是 modules；因为使用单一状态树，应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时，store 对象就有可能变得相当臃肿。所以将 store 分割成模块（module）。每个模块拥有自己的 state、mutations、actions、getters，甚至是嵌套子模块，从上至下进行同样方式的分割。</p><p>在 module 文件新建 moduleA.js 和 moduleB.js 文件。在文件中写入</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> state=&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> getters=&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> mutations=&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> actions=&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    state,</span><br><span class="line">    getters,</span><br><span class="line">    mutations,</span><br><span class="line">    actions</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>然后再 index.js 引入模块</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> Vuex <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line">Vue.use(Vuex)</span><br><span class="line"><span class="keyword">import</span> moduleA <span class="keyword">from</span> <span class="string">'./module/moduleA'</span></span><br><span class="line"><span class="keyword">import</span> moduleB <span class="keyword">from</span> <span class="string">'./module/moduleB'</span></span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    modules:&#123;</span><br><span class="line">        moduleA,</span><br><span class="line">        moduleB</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> store</span><br></pre></td></tr></table></figure><h1 id="在模块中，getter-和-mutation-接收的第一个参数-state-，是全局的还是模块的？"><a href="#在模块中，getter-和-mutation-接收的第一个参数-state-，是全局的还是模块的？" class="headerlink" title="在模块中，getter 和 mutation 接收的第一个参数 state ，是全局的还是模块的？"></a>在模块中，getter 和 mutation 接收的第一个参数 state ，是全局的还是模块的？</h1><p>第一个参数 state 是模块的 state，也就是局部的 state。</p><h1 id="在模块中，getter-和-mutation-和-action-中怎么访问全局的-state-和getter？"><a href="#在模块中，getter-和-mutation-和-action-中怎么访问全局的-state-和getter？" class="headerlink" title="在模块中，getter 和 mutation 和 action 中怎么访问全局的 state 和getter？"></a>在模块中，getter 和 mutation 和 action 中怎么访问全局的 state 和getter？</h1><ul><li>在 getter 中可以通过第三个参数 rootState 访问到全局的 state，可以通过第四个参数 rootGetters 访问到全局的 getter。</li><li>在 mutation 中不可以访问全局的 state 和 getter，只能访问到局部的 state。</li><li>在 action 中第一个参数 context 中的 <code>context.rootState</code> 访问到全局的 state，<code>context.rootGetters</code> 访问到全局的 getter。</li></ul><h1 id="在组件怎么访问-Vuex-模块中的-getter-和-state-，怎么提交-mutation-和-action？"><a href="#在组件怎么访问-Vuex-模块中的-getter-和-state-，怎么提交-mutation-和-action？" class="headerlink" title="在组件怎么访问 Vuex 模块中的 getter 和 state ，怎么提交 mutation 和 action？"></a>在组件怎么访问 Vuex 模块中的 getter 和 state ，怎么提交 mutation 和 action？</h1><ul><li>直接通过 <code>this.$store.getters</code> 和 <code>this.$store.state</code> 来访问模块中的 getter 和 state。</li><li>直接通过 <code>this.$store.commit(&#39;mutationA&#39;, data)</code> 提交模块中的 mutation。</li><li>直接通过 <code>this.$store.dispatch(&#39;actionA, data&#39;)</code> 提交模块中的 action。</li></ul><h1 id="用过-Vuex-模块的命名空间吗？为什么使用，怎么使用。"><a href="#用过-Vuex-模块的命名空间吗？为什么使用，怎么使用。" class="headerlink" title="用过 Vuex 模块的命名空间吗？为什么使用，怎么使用。"></a>用过 Vuex 模块的命名空间吗？为什么使用，怎么使用。</h1><p>默认情况下，模块内部的 action、mutation 和 getter 是注册在全局命名空间，如果多个模块中 action、mutation 的命名是一样的，那么提交 mutation、action时，将会触发所有模块中命名相同的 mutation、action。</p><p>这样有太多的耦合，如果要使你的模块具有更高的封装度和复用性，你可以通过添加 <code>namespaced: true</code> 的方式使其成为命名空间的模块。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span>&#123;</span><br><span class="line">    namespaced: <span class="literal">true</span>,</span><br><span class="line">    state,</span><br><span class="line">    getters,</span><br><span class="line">    mutations,</span><br><span class="line">    actions</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="怎么在带命名空间的模块内提交全局的-mutation-和-action？"><a href="#怎么在带命名空间的模块内提交全局的-mutation-和-action？" class="headerlink" title="怎么在带命名空间的模块内提交全局的 mutation 和 action？"></a>怎么在带命名空间的模块内提交全局的 mutation 和 action？</h1><p>将 { root： true} 作为第三参数传给 dispatch 或 commit 即可。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.$store.dispatch(<span class="string">'actionA'</span>, <span class="literal">null</span>, &#123;<span class="attr">root</span>: <span class="literal">true</span>&#125;)</span><br><span class="line"><span class="keyword">this</span>.$store.commit(<span class="string">'mutationA'</span>, <span class="literal">null</span>, &#123;<span class="attr">root</span>: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure><h1 id="怎么在带命名空间的模块内注册全局的-action？"><a href="#怎么在带命名空间的模块内注册全局的-action？" class="headerlink" title="怎么在带命名空间的模块内注册全局的 action？"></a>怎么在带命名空间的模块内注册全局的 action？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">actions: &#123;</span><br><span class="line">    actionA: &#123;</span><br><span class="line">        root: <span class="literal">true</span>,</span><br><span class="line">        handler (context, data) &#123; ... &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="组件中怎么提交-modules-中的带命名空间的-moduleA-中的-mutationA？"><a href="#组件中怎么提交-modules-中的带命名空间的-moduleA-中的-mutationA？" class="headerlink" title="组件中怎么提交 modules 中的带命名空间的 moduleA 中的 mutationA？"></a>组件中怎么提交 modules 中的带命名空间的 moduleA 中的 mutationA？</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.$store.commit(<span class="string">'moduleA/mutationA'</span>, data)</span><br></pre></td></tr></table></figure><h1 id="怎么使用-mapState，mapGetters，mapActions-和-mapMutations-这些函数来绑定带命名空间的模块？"><a href="#怎么使用-mapState，mapGetters，mapActions-和-mapMutations-这些函数来绑定带命名空间的模块？" class="headerlink" title="怎么使用 mapState，mapGetters，mapActions 和 mapMutations 这些函数来绑定带命名空间的模块？"></a>怎么使用 mapState，mapGetters，mapActions 和 mapMutations 这些函数来绑定带命名空间的模块？</h1><p>首先使用 <code>createNamespacedHelpers</code> 创建基于某个命名空间辅助函数</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createNamespacedHelpers &#125; <span class="keyword">from</span> <span class="string">'vuex'</span>;</span><br><span class="line"><span class="keyword">const</span> &#123; mapState, mapActions &#125; = createNamespacedHelpers(<span class="string">'moduleA'</span>);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    computed: &#123;</span><br><span class="line">        <span class="comment">// 在 `module/moduleA` 中查找</span></span><br><span class="line">        ...mapState(&#123;</span><br><span class="line">            a: <span class="function"><span class="params">state</span> =&gt;</span> state.a,</span><br><span class="line">            b: <span class="function"><span class="params">state</span> =&gt;</span> state.b</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    methods: &#123;</span><br><span class="line">        <span class="comment">// 在 `module.moduleA` 中查找</span></span><br><span class="line">        ...mapActions([</span><br><span class="line">            <span class="string">'actionA'</span>,</span><br><span class="line">            <span class="string">'actionB'</span></span><br><span class="line">        ])</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="Vuex-插件有用过吗？怎么用简单介绍一下？"><a href="#Vuex-插件有用过吗？怎么用简单介绍一下？" class="headerlink" title="Vuex 插件有用过吗？怎么用简单介绍一下？"></a>Vuex 插件有用过吗？怎么用简单介绍一下？</h1><p>Vuex 插件就是一个函数，它接收 store 作为唯一参数。在 Vuex.Store 构造器选项 plugins 引入。在 store/plugin.js 文件中写入</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">createPlugin</span>(<span class="params">param</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">store</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>然后再 store/index.js 文件中写入</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> createPlugin <span class="keyword">from</span> <span class="string">'./plugin.js'</span></span><br><span class="line"><span class="keyword">const</span> myPlugin = createPlugin()</span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    <span class="comment">// ... </span></span><br><span class="line">    plugins: [myPlugin]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><h1 id="在-Vuex-插件中怎么监听组件中提交-mutation-和-action？"><a href="#在-Vuex-插件中怎么监听组件中提交-mutation-和-action？" class="headerlink" title="在 Vuex 插件中怎么监听组件中提交 mutation 和 action？"></a>在 Vuex 插件中怎么监听组件中提交 mutation 和 action？</h1><ul><li>用 Vuex.Store 的实例方法 <code>subscribe</code> 监听组件中提交 mutation</li><li>用 Vuex.Store 的实例方法 <code>subscribeAction</code> 监听组件中提交 action 在 store/plugin.js 文件中写入</li></ul><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">createPlugin</span>(<span class="params">param</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">store</span> =&gt;</span> &#123;</span><br><span class="line">        store.subscribe(<span class="function">(<span class="params">mutation, state</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(mutation.type)<span class="comment">//是那个mutation</span></span><br><span class="line">            <span class="built_in">console</span>.log(mutation.payload)</span><br><span class="line">            <span class="built_in">console</span>.log(state)</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="comment">// store.subscribeAction((action, state) =&gt; &#123;</span></span><br><span class="line">        <span class="comment">//     console.log(action.type)//是那个action</span></span><br><span class="line">        <span class="comment">//     console.log(action.payload)//提交action的参数</span></span><br><span class="line">        <span class="comment">// &#125;)</span></span><br><span class="line">        store.subscribeAction(&#123;</span><br><span class="line">            before: <span class="function">(<span class="params">action, state</span>) =&gt;</span> &#123;<span class="comment">//提交action之前</span></span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">`before action <span class="subst">$&#123;action.type&#125;</span>`</span>)</span><br><span class="line">            &#125;,</span><br><span class="line">            after: <span class="function">(<span class="params">action, state</span>) =&gt;</span> &#123;<span class="comment">//提交action之后</span></span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">`after action <span class="subst">$&#123;action.type&#125;</span>`</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>然后再 store/index.js 文件中写入</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> createPlugin <span class="keyword">from</span> <span class="string">'./plugin.js'</span></span><br><span class="line"><span class="keyword">const</span> myPlugin = createPlugin()</span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  plugins: [myPlugin]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><h1 id="在-v-model-上怎么用-Vuex-中-state-的值？"><a href="#在-v-model-上怎么用-Vuex-中-state-的值？" class="headerlink" title="在 v-model 上怎么用 Vuex 中 state 的值？"></a>在 v-model 上怎么用 Vuex 中 state 的值？</h1><p>需要通过 computed 计算属性来转换。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;input v-model=<span class="string">"message"</span> /&gt;</span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">computed: &#123;</span><br><span class="line">    message: &#123;</span><br><span class="line">        <span class="keyword">get</span> () &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.$store.state.message</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="keyword">set</span> (value) &#123;</span><br><span class="line">            <span class="keyword">this</span>.$store.commit(<span class="string">'updateMessage'</span>, value)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="Vuex-的严格模式是什么，有什么作用，怎么开启？"><a href="#Vuex-的严格模式是什么，有什么作用，怎么开启？" class="headerlink" title="Vuex 的严格模式是什么，有什么作用，怎么开启？"></a>Vuex 的严格模式是什么，有什么作用，怎么开启？</h1><p>在严格模式下，无论何时发生了状态变更且不是由 mutation 函数引起的，将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到。</p><p>在 Vuex.Store 构造器选项中开启，如下</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    strict: <span class="literal">true</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></div><footer class="post-footer"><div class="post-tags"><a href="/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/article/85fb390f.html" rel="next" title="微信小程序开发"><i class="fa fa-chevron-left"></i> 微信小程序开发</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/article/936297c4.html" rel="prev" title="Cookies、Session、sessionStorage和localStorage的区别？">Cookies、Session、sessionStorage和localStorage的区别？<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article><div class="post-spread"></div></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><section class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="http://ww1.sinaimg.cn/large/007WurYGgy1ge8nxttd9nj302s02s0si.jpg" alt="King-XiYu"><p class="site-author-name" itemprop="name">King-XiYu</p><p class="site-description motion-element" itemprop="description">有志者事竟成</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">37</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/index.html"><span class="site-state-item-count">11</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/index.html"><span class="site-state-item-count">10</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://gitee.com/King-XiYu" target="_blank" title="Gitee"><i class="fa fa-fw fa-hand-o-right"></i> Gitee</a></span><span class="links-of-author-item"><a href="https://github.com/King-XiYu" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i> GitHub</a></span></div><div class="links-of-blogroll motion-element links-of-blogroll-inline"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"> <a href="https://www.baidu.com/" title="度娘" target="_blank">度娘</a></li><li class="links-of-blogroll-item"> <a href="https://www.google.com/" title="Google" target="_blank">Google</a></li></ul></div></div></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#什么是-Vuex-？"><span class="nav-number">1.</span> <span class="nav-text">什么是 Vuex ？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-解决了什么问题？"><span class="nav-number">2.</span> <span class="nav-text">Vuex 解决了什么问题？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#什么时候用-Vuex-？"><span class="nav-number">3.</span> <span class="nav-text">什么时候用 Vuex ？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么引用-Vuex-？"><span class="nav-number">4.</span> <span class="nav-text">怎么引用 Vuex ？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-的5个核心属性是什么？"><span class="nav-number">5.</span> <span class="nav-text">Vuex 的5个核心属性是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中状态存储在哪里，怎么改变它？"><span class="nav-number">6.</span> <span class="nav-text">Vuex 中状态存储在哪里，怎么改变它？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex中状态是对象时，使用时要注意什么？"><span class="nav-number">7.</span> <span class="nav-text">Vuex中状态是对象时，使用时要注意什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么在组件中批量使用-Vuex-的-state-状态？"><span class="nav-number">8.</span> <span class="nav-text">怎么在组件中批量使用 Vuex 的 state 状态？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中要从-state-派生一些状态出来，且多个组件使用它，该怎么做？"><span class="nav-number">9.</span> <span class="nav-text">Vuex 中要从 state 派生一些状态出来，且多个组件使用它，该怎么做？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么通过-getter-来实现在组件内可以通过特定条件来获取-state-的状态？"><span class="nav-number">10.</span> <span class="nav-text">怎么通过 getter 来实现在组件内可以通过特定条件来获取 state 的状态？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么在组件中批量使用-Vuex-的-getter-属性"><span class="nav-number">11.</span> <span class="nav-text">怎么在组件中批量使用 Vuex 的 getter 属性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么再组件中批量给-Vuex-的-getter-属性取别名并使用"><span class="nav-number">12.</span> <span class="nav-text">怎么再组件中批量给 Vuex 的 getter 属性取别名并使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在-Vuex-的-state-中有个状态-number-表示货物数量，在组件怎么改变它。"><span class="nav-number">13.</span> <span class="nav-text">在 Vuex 的 state 中有个状态 number 表示货物数量，在组件怎么改变它。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在-Vuex-中使用-mutation-要注意什么。"><span class="nav-number">14.</span> <span class="nav-text">在 Vuex 中使用 mutation 要注意什么。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在组件中多次提交同一个-mutation，怎么写使用更方便。"><span class="nav-number">15.</span> <span class="nav-text">在组件中多次提交同一个 mutation，怎么写使用更方便。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中-action-和-mutation-有什么区别？"><span class="nav-number">16.</span> <span class="nav-text">Vuex 中 action 和 mutation 有什么区别？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中-action-和-mutation-有什么相同点？"><span class="nav-number">17.</span> <span class="nav-text">Vuex 中 action 和 mutation 有什么相同点？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在组件中多次提交同一个-action-，怎么写使用更方便。"><span class="nav-number">18.</span> <span class="nav-text">在组件中多次提交同一个 action ，怎么写使用更方便。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中-action-通常是异步的，那么如何知道-action-什么时候结束呢？"><span class="nav-number">19.</span> <span class="nav-text">Vuex 中 action 通常是异步的，那么如何知道 action 什么时候结束呢？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-中有两个-action，分别是-actionA-和-actionB，其内都是异步操作，在-actionB-要提交-actionA，需在-actionA-处理结束在处理其他操作，怎么实现"><span class="nav-number">20.</span> <span class="nav-text">Vuex 中有两个 action，分别是 actionA 和 actionB，其内都是异步操作，在 actionB 要提交 actionA，需在 actionA 处理结束在处理其他操作，怎么实现?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#有用过-Vuex-模板吗，为什么要使用，怎么使用。"><span class="nav-number">21.</span> <span class="nav-text">有用过 Vuex 模板吗，为什么要使用，怎么使用。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在模块中，getter-和-mutation-接收的第一个参数-state-，是全局的还是模块的？"><span class="nav-number">22.</span> <span class="nav-text">在模块中，getter 和 mutation 接收的第一个参数 state ，是全局的还是模块的？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在模块中，getter-和-mutation-和-action-中怎么访问全局的-state-和getter？"><span class="nav-number">23.</span> <span class="nav-text">在模块中，getter 和 mutation 和 action 中怎么访问全局的 state 和getter？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在组件怎么访问-Vuex-模块中的-getter-和-state-，怎么提交-mutation-和-action？"><span class="nav-number">24.</span> <span class="nav-text">在组件怎么访问 Vuex 模块中的 getter 和 state ，怎么提交 mutation 和 action？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#用过-Vuex-模块的命名空间吗？为什么使用，怎么使用。"><span class="nav-number">25.</span> <span class="nav-text">用过 Vuex 模块的命名空间吗？为什么使用，怎么使用。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么在带命名空间的模块内提交全局的-mutation-和-action？"><span class="nav-number">26.</span> <span class="nav-text">怎么在带命名空间的模块内提交全局的 mutation 和 action？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么在带命名空间的模块内注册全局的-action？"><span class="nav-number">27.</span> <span class="nav-text">怎么在带命名空间的模块内注册全局的 action？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#组件中怎么提交-modules-中的带命名空间的-moduleA-中的-mutationA？"><span class="nav-number">28.</span> <span class="nav-text">组件中怎么提交 modules 中的带命名空间的 moduleA 中的 mutationA？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#怎么使用-mapState，mapGetters，mapActions-和-mapMutations-这些函数来绑定带命名空间的模块？"><span class="nav-number">29.</span> <span class="nav-text">怎么使用 mapState，mapGetters，mapActions 和 mapMutations 这些函数来绑定带命名空间的模块？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-插件有用过吗？怎么用简单介绍一下？"><span class="nav-number">30.</span> <span class="nav-text">Vuex 插件有用过吗？怎么用简单介绍一下？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在-Vuex-插件中怎么监听组件中提交-mutation-和-action？"><span class="nav-number">31.</span> <span class="nav-text">在 Vuex 插件中怎么监听组件中提交 mutation 和 action？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在-v-model-上怎么用-Vuex-中-state-的值？"><span class="nav-number">32.</span> <span class="nav-text">在 v-model 上怎么用 Vuex 中 state 的值？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vuex-的严格模式是什么，有什么作用，怎么开启？"><span class="nav-number">33.</span> <span class="nav-text">Vuex 的严格模式是什么，有什么作用，怎么开启？</span></a></li></ol></div></div></section><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2020</span><span class="with-love"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">宇宙特别帅</span></div></div></footer></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script><script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script><script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="//cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: true,
        appId: '9DODHXKj6rr1cK4oO07iVBX3-gzGzoHsz',
        appKey: 'aJaxxns4VN5WV9nMimT9aSb1',
        placeholder: 'ヾﾉ≧∀≦)o 来呀！吐槽一番吧！',
        avatar:'mp',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script><script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script><script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script><script>AV.initialize("9DODHXKj6rr1cK4oO07iVBX3-gzGzoHsz","aJaxxns4VN5WV9nMimT9aSb1")</script><script>function showTime(e){var t=new AV.Query(e),c=[],u=$(".leancloud_visitors");u.each(function(){c.push($(this).attr("id").trim())}),t.containedIn("url",c),t.find().done(function(e){var t=".leancloud-visitors-count";if(0!==e.length){for(var n=0;n<e.length;n++){var o=e[n],i=o.get("url"),s=o.get("time"),r=document.getElementById(i);$(r).find(t).text(s)}for(n=0;n<c.length;n++){i=c[n],r=document.getElementById(i);var l=$(r).find(t);""==l.text()&&l.text(0)}}else u.find(t).text(0)}).fail(function(e,t){console.log("Error: "+t.code+" "+t.message)})}function addCount(i){var e=$(".leancloud_visitors"),s=e.attr("id").trim(),r=e.attr("data-flag-title").trim(),t=new AV.Query(i);t.equalTo("url",s),t.find({success:function(e){if(0<e.length){var t=e[0];t.fetchWhenSave(!0),t.increment("time"),t.save(null,{success:function(e){$(document.getElementById(s)).find(".leancloud-visitors-count").text(e.get("time"))},error:function(e,t){console.log("Failed to save Visitor num, with error message: "+t.message)}})}else{var n=new i,o=new AV.ACL;o.setPublicReadAccess(!0),o.setPublicWriteAccess(!0),n.setACL(o),n.set("title",r),n.set("url",s),n.set("time",1),n.save(null,{success:function(e){$(document.getElementById(s)).find(".leancloud-visitors-count").text(e.get("time"))},error:function(e,t){console.log("Failed to create")}})}},error:function(e){console.log("Error:"+e.code+" "+e.message)}})}$(function(){var e=AV.Object.extend("Counter");1==$(".leancloud_visitors").length?addCount(e):1<$(".post-title-link").length&&showTime(e)})</script><script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script><script type="text/javascript" src="/js/src/clipboard-use.js"></script></body></html>